﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Graph = System.Windows.Forms.DataVisualization.Charting;
using System.Threading;
using Communicator;
using System.IO;

namespace SignLockerTest
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
             _theChart = new SignChart(panelChart);
        }

        protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
        {
            switch (keyData)
            {
                case Keys.Control | Keys.D:
                    _logForm.Show();
                    break;
            }
            return base.ProcessCmdKey(ref msg, keyData);
        }

        private Server _server;
        private LogForm _logForm = new LogForm();
        private SavedFileForm _savedForm = new SavedFileForm();
        private int _downloadCount = 0;
        private string _inputFolder = "Input";

        private SignChart _theChart;

        private void AppendLog(string mess)
        {
            string msg = string.Format("[{0}] {1}\n", DateTime.Now, mess);
            Invoke(new ThreadStart(() =>
            {
                _logForm.TextBoxLog.AppendText(msg);
            }));
        }

        private void btnStart_Click(object sender, EventArgs e)
        {
            if (btnStart.Text == "Start")
            {
                _server = new Server(int.Parse(txtServerPort.Text));
                _server.FpClientConnected = (x, y) => 
                    { 
                        AppendLog(string.Format("Client '{0}' connected !", y));
                        Invoke(new ThreadStart(() => { lblClientCount.Text = _server.ClientCount.ToString(); }));
                    };
                _server.FpClientDisconnected = (x, y) => 
                    {
                        AppendLog(string.Format("Client '{0}' disconnected !", y)); 
                        Invoke(new ThreadStart(() => { lblClientCount.Text = _server.ClientCount.ToString(); }));
                    };
                _server.FpSend = (x, y) => { AppendLog(string.Format("Send: '{0}'", y)); };
                _server.FpReceive = (x, y) => 
                    { 
                        AppendLog(string.Format("Recv: '{0}'", y)); DownloadFunc(y);
                        _downloadCount++;
                        Invoke(new ThreadStart(() => { lblSaved.Text = _downloadCount.ToString(); }));
                    };

                _server.Start();

                if (_server.Started)
                {
                    AppendLog("Server started !");
                    btnStart.Text = "Stop";
                }
            }
            else
            {
                btnStart.Text = "Start";
                if (_server != null && _server.Started)
                    _server.Stop();
            }
        }

        private void DownloadFunc(string content)
        {
            if (!Directory.Exists(_inputFolder))
                Directory.CreateDirectory(_inputFolder);

            DateTime now = DateTime.Now;
            string fileName = string.Format("{1}/{0}.txt", now.ToString("yyyyMMddhhmmss"), _inputFolder);
            using (StreamWriter w = new StreamWriter(fileName))
                w.Write(content);

            FileInfo file = new FileInfo(fileName);
            AppendLog(string.Format("Save as '{0}'", file.FullName));
            Invoke(new ThreadStart(() => 
                { 
                    _savedForm.Add(file.FullName);
                    txtDownloadedFile.Text = file.FullName;
                    txtTestFile.Text = file.FullName;
                }));
        }

        private void Form1_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (_server!= null && _server.Started)
                _server.Stop();
        }

        private void lblSaved_Click(object sender, EventArgs e)
        {
            _savedForm.Show();
        }

        private void chbUseDownloadedFile_CheckedChanged(object sender, EventArgs e)
        {
            try
            {
                if (chbUseDownloadedFile.Checked)
                {
                    txtTestFile.Text = txtDownloadedFile.Text;
                    txtTestFile.Enabled = false;
                    btnBrowseTestFile.Enabled = false;
                }
                else
                {
                    txtTestFile.Enabled = true;
                    btnBrowseTestFile.Enabled = true;
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void btnDrawTest_Click(object sender, EventArgs e)
        {
            try
            {
                string xmlContent = string.Empty;
                using (StreamReader reader = new StreamReader(txtTestFile.Text))
                    xmlContent = reader.ReadToEnd();

                string name = txtTestName.Text;
                _theChart.DrawSeries(name, name, SignParser.Parser(xmlContent).ToArray());
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void btnBrowseTestFile_Click(object sender, EventArgs e)
        {
            OpenFileDialog dialog = new OpenFileDialog();
            var res = dialog.ShowDialog();
            if (res == System.Windows.Forms.DialogResult.OK)
            {
                txtTestFile.Text = dialog.FileName;
            }
        }

        #region Up, Down, Left, Right Button
        private void btnMoveUp_Click(object sender, EventArgs e)
        {
            try
            {
                _theChart.Move(txtTestName.Text, Direction.Up, double.Parse(txtStep.Text));
            }
            catch (Exception lỗi)
            {
                MessageBox.Show(lỗi.ToString());
            }
        }

        private void btnMoveRight_Click(object sender, EventArgs e)
        {
            try
            {
                _theChart.Move(txtTestName.Text, Direction.Right, double.Parse(txtStep.Text));
            }
            catch (Exception lỗi)
            {
                MessageBox.Show(lỗi.ToString());
            }
        }

        private void btnMoveDown_Click(object sender, EventArgs e)
        {
            try
            {
                _theChart.Move(txtTestName.Text, Direction.Down, double.Parse(txtStep.Text));
            }
            catch (Exception lỗi)
            {
                MessageBox.Show(lỗi.ToString());
            }
        }

        private void btnMoveLeft_Click(object sender, EventArgs e)
        {
            try
            {
                _theChart.Move(txtTestName.Text, Direction.Left, double.Parse(txtStep.Text));
            }
            catch (Exception lỗi)
            {
                MessageBox.Show(lỗi.ToString());
            }
        } 
        #endregion
    }
}
